<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NSelect,
  type FormRules,
  NTreeSelect,
  NScrollbar,
  NTag
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h, watch, onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import type { itemModel } from '@/api/item'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'
import VScope from '@/views/OA/Common/Scope.vue'

const message = useMessage()
const router = useRouter()
const listdjOption = ref([])
const listlxOption = ref([])
const listdjrOption = ref([])
const modalQrVisible = ref(false)
const formRef = ref<FormInst | null>(null)
const formRef2 = ref<FormInst | null>(null)
onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})

const tableData = ref<itemModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}

const formValue2 = reactive({
  receiver: null as string | null,
  receivers: [] as Contact[]
})
// 督交人
interface Contact {
  identifyingId: string
  typeName: string
  parentId: string
  typeCode: string
  deptId: string
  fullId: string
}

const v1 = () => {
  formRef2.value?.validate(
    () => {},
    (r) => r.key === 'receivers'
  )
}
const contactsModalVisible = ref(false)
const handleContactsModalSubmit = (v: Contact[]) => {
  formValue2.receiver = v.map((e) => e.typeName).join(',')
  formValue2.receivers = v
  contactsModalVisible.value = false
  v1()
}
const handleDeleteContact = (index: number) => {
  formValue2.receivers?.splice(index, 1)
  formValue2.receiver = formValue2.receivers.map((e) => e.typeName).join(',')
  v1()
}

const formValue = reactive({
  remark: null,
  storagePlace: null
})

const rules: FormRules = {
  storagePlace: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请输入存放位置')
      if (value?.length > 100) return new Error('存放位置字数不得超过100')
      return true
    }
  },
  remark: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value && value.length > 500) return new Error('备注字数不得超过500')
      return true
    }
  }
}
const modalVisible = ref(false)
const modalPointVisible = ref(false)
const modalSaveVisible = ref(false)
const route = useRoute()
const [form, resetForm] = useQueryForm(
  reactive({
    itemName: null,
    djStatusCode: null,
    itemTypeCode: null
  }),
  () => {
    form.itemName = null
    form.djStatusCode = null
    form.itemTypeCode = null
  }
)
const columns: DataTableColumns<itemModel> = [
  {
    type: 'selection',
    fixed: 'left',
    width: '2rem'
  },
  {
    title: '序号',
    key: 'orderIndex',
    render: (_, i) => {
      return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
    },
    width: '5rem',
    align: 'center'
  },
  {
    title: '征集品名称',
    key: 'itemName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '批次编号',
    key: 'batchCode',
    width: '10rem',
    align: 'center'
  },
  {
    title: '征集线索信息',
    key: 'clueName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '类型',
    key: 'itemType',
    width: '10rem',
    align: 'center'
  },
  {
    title: '点交状态',
    key: 'djStatus',
    width: '10rem',
    align: 'center'
  },
  {
    title: '未点交存放地',
    key: 'storagePlace',
    width: '10rem',
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: '25rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleAdd(e),
          style: {
            display: e.dj ? 'inline-block' : 'none'
          }
        },
        {
          default: () => '点交'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleSave(e),
          style: {
            display: e.zc ? 'inline-block' : 'none'
          }
        },
        {
          default: () => '暂存'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e),
          style: {
            display: e.xq ? 'inline-block' : 'none'
          }
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          quaternary: true,
          color: '#5fb17f',
          style: {
            display: e.djqr ? 'inline-block' : 'none'
          },
          onClick: async () => {
            handleQr(e)
          }
        },
        {
          default: () => '点交确认'
        }
      )
    ]
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<HttpResponsePagination<itemModel>>({
    module: 'item',
    api: 'djItemsNew',
    override: {
      params: {
        itemName: form.itemName,
        djStatusCode: form.djStatusCode,
        itemTypeCode: form.itemTypeCode,
        page: paginationReactive.page,
        limit: paginationReactive.pageSize
      }
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}
const addCount = ref({
  clicked: null,
  notClicked: null,
  total: null,
  identify: null,
  notIdentify: null
})
//点交状态下拉框
const queryDjAdd = async () => {
  listdjOption.value = []
  const [error, res] = await sendRequest<HttpResponsePagination<itemModel>>({
    module: 'item',
    api: 'batchStatusDropBox'
  })
  if (error) return message.error(error.message)
  // @ts-ignore
  res.data.forEach((e) => {
    // @ts-ignore
    listdjOption.value.push({ label: e.name, value: e.value })
  })
}
//征集品版本类型下拉框
const queryLxAdd = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseCollectClassificationConfig',
    api: 'listTreeAll',
    override: {
      params: {
        statusCode: 'A4901'
      }
    }
  })
  if (error) return message.error(error.message)
  listlxOption.value = res.data
}
//督交人下拉框
const querydjrAdd = async () => {
  listdjrOption.value = []
  const [error, res] = await sendRequest<HttpResponsePagination<itemModel>>({
    module: 'item',
    api: 'supervisor'
  })
  if (error) return message.error(error.message)
  // @ts-ignore
  res.data.forEach((e) => {
    // @ts-ignore
    listdjrOption.value.push({ label: e.userName, value: e.userId })
  })
}

const queryAdd = async () => {
  const [error, res] = await sendRequest<HttpResponsePagination<itemModel>>({
    module: 'item',
    api: 'subItemStat'
  })
  if (error) return message.error(error.message)
  // @ts-ignore
  addCount.value = res.data
}
const handleDetail = (e: any) => {
  router.push({ name: 'CollectingItemsDetail', params: { id: e.batchId, subItemId: e.subItemId } })
}
const handleSave = (e: any) => {
  subItems.value = [{ batchId: e.batchId, itemId: e.itemId, subItemId: e.subItemId }]
  modalSaveVisible.value = true
}
const handleAdd = (e: any) => {
  querydjrAdd()
  subItems.value = [{ batchId: e.batchId, itemId: e.itemId, subItemId: e.subItemId }]
  modalPointVisible.value = true
}
const handleAddP = () => {
  if (djIds.value.length === 0) return message.error('请至少选择一项！')
  querydjrAdd()
  modalPointVisible.value = true
}
const ids = ref()
// const handleDelete = (id: any) => {
//   ids.value = id
//   modalVisible.value = true
// }
const againDelete = async () => {
  const [error] = await sendRequest<HttpResponse>({
    module: 'item',
    api: 'delete',
    override: {
      data: [ids.value]
    }
  })
  if (error) return message.error(error.message)
  queryTableData(true)
  modalVisible.value = false
}
const eQr = ref()
const handleQr = async (e: any) => {
  eQr.value = e
  modalQrVisible.value = true
}
const againHandleQr = async () => {
  const [error, res] = await sendRequest<HttpResponsePagination<itemModel>>({
    module: 'item',
    api: 'clickConfirm',
    override: {
      data: {
        subItems: [
          { batchId: eQr.value.batchId, itemId: eQr.value.itemId, subItemId: eQr.value.subItemId }
        ]
      }
    }
  })
  if (error) return message.error(error.message)
  message.success(res.msg)
  queryTableData(true)
  modalQrVisible.value = false
}
const submitPoint = () => {
  formRef2.value?.validate(async (err) => {
    if (err) return
    const [error, res] = await sendRequest<HttpResponsePagination<itemModel>>({
      module: 'item',
      api: 'addDjRecord',
      override: {
        data: {
          receiver: formValue2.receiver,
          subItems: subItems.value
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    modalPointVisible.value = false
    formValue2.receivers = []
    formValue2.receiver = null
    rowKeys.value = []
    queryTableData(true)
    message.success(res.msg)
  })
}
const submitSave = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    const [error, res] = await sendRequest<HttpResponsePagination<itemModel>>({
      module: 'item',
      api: 'temporaryStorage',
      override: {
        data: {
          storagePlace: formValue.storagePlace,
          remark: formValue.remark,
          subItems: subItems.value
        }
      }
    })
    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    modalSaveVisible.value = false
    message.success('暂存成功！')
    formValue.remark = null
    formValue.storagePlace = null
    queryTableData(true)
  })
}
const rowKey: any = (row: any) => row.subItemId || ''
const rowKeys = ref([])
const djIds = ref([])
const subItems = ref([
  {
    batchId: '',
    itemId: '',
    subItemId: ''
  }
])
const rowKeysChange = (v: any, a: any) => {
  rowKeys.value = v
  djIds.value = v
  subItems.value = []
  a.forEach((e: any) => {
    subItems.value.push({ batchId: e.batchId, itemId: e.itemId, subItemId: e.subItemId })
  })
}

const batchDjAuth = ref(false)

onMounted(() => {
  queryTableData(true)
  queryDjAdd()
  queryLxAdd()

  sendRequest({
    module: 'batch',
    api: 'batchDjAuth'
  }).then(([error, res]) => {
    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    batchDjAuth.value = res.data
  })
})
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route,
  () => {
    if (route.path == '/collectionManagement/CollectionProcess/CollectingItems/index') {
      queryTableData(true)
      queryAdd()
      window.addEventListener('keyup', keyUpDown, false) // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <!-- <div class="box">
    <div class="boxT">
      <div class="imgS">
        <img src="@/assets/images/pic1.png" />
      </div>
      <div class="fontS">
        <div class="topF">
          <span>{{ addCount.total }}</span>
          <span>件</span>
        </div>
        <div class="bottomF">所有征集品</div>
      </div>
    </div>
    <div class="boxT">
      <div class="imgS">
        <img src="@/assets/images/pic2.png" />
      </div>
      <div class="fontS">
        <div class="topF">
          <span>{{ addCount.identify }}</span>
          <span>件</span>
        </div>
        <div class="bottomF">已鉴定</div>
      </div>
    </div>
    <div class="boxT">
      <div class="imgS">
        <img src="@/assets/images/pic3.png" />
      </div>
      <div class="fontS">
        <div class="topF">
          <span>{{ addCount.notIdentify }}</span>
          <span>件</span>
        </div>
        <div class="bottomF">未鉴定</div>
      </div>
    </div>
    <div class="boxT">
      <div class="imgS">
        <img src="@/assets/images/pic4.png" />
      </div>
      <div class="fontS">
        <div class="topF">
          <span>{{ addCount.clicked }}</span>
          <span>件</span>
        </div>
        <div class="bottomF">已点交</div>
      </div>
    </div>
    <div class="boxT">
      <div class="imgS">
        <img src="@/assets/images/pic5.png" />
      </div>
      <div class="fontS">
        <div class="topF">
          <span>{{ addCount.notClicked }}</span>
          <span>件</span>
        </div>
        <div class="bottomF">未点交</div>
      </div>
    </div>
  </div> -->
  <!-- <div class="line"></div> -->
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          require-mark-placement="left"
          inline
        >
          <NFormItem label="征集品名称:">
            <NInput
              placeholder="输入征集品名称"
              v-model:value="form.itemName"
            />
          </NFormItem>
          <NFormItem label="点交状态:">
            <NSelect
              :options="listdjOption"
              v-model:value="form.djStatusCode"
              placeholder="请选择点交状态"
              clearable
              style="width: 200px"
            />
          </NFormItem>
          <NFormItem label="类型:">
            <NTreeSelect
              :options="listlxOption"
              v-model:value="form.itemTypeCode"
              placeholder="请选择版本类型"
              clearable
              style="width: 200px"
              key-field="classificationCode"
              label-field="classificationName"
              children-field="childList"
            />
          </NFormItem>
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px; margin-right: 10px"
              ghost
              @click="queryTableData(true)"
              :loading="tableLoading"
            >
              查询
            </NButton>
            <NButton
              type="primary"
              ghost
              style="width: 78px"
              @click="resetForm"
            >
              重置
            </NButton>
          </NFormItem>
        </NForm>
        <NSpace
          v-if="batchDjAuth"
          align="end"
        >
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAddP"
          >
            批量点交
          </NButton>
        </NSpace>
      </NSpace>
    </template>
    <template #table="props">
      <NDataTable
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
        :rowKey="rowKey"
        :checked-row-keys="rowKeys"
        @update:checked-row-keys="rowKeysChange"
      />
    </template>
    <template #pagination>
      <NPagination
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
        show-size-picker
        show-quick-jumper
        :suffix="() => '页'"
      >
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
  <!-- 删除弹窗 -->
  <NModal
    :auto-focus="false"
    v-model:show="modalVisible"
  >
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
  <!-- 点交弹窗 -->
  <NModal
    :auto-focus="false"
    v-model:show="modalPointVisible"
  >
    <VDialogContent
      @close="
        ;(modalPointVisible = false), (formValue2.receivers = []), (formValue2.receiver = null)
      "
      @submit="submitPoint"
      title="点交"
    >
      <NSpace>
        <NForm
          ref="formRef2"
          :model="formValue2"
          label-placement="left"
          :label-width="85"
          label-align="right"
          require-mark-placement="left"
        >
          <NSpace>
            <NFormItem
              label="督交人:"
              path="receivers"
              :rule="{
                key: 'receivers',
                required: true,
                message: '请选择督交人',
                type: 'array',
                trigger: ['blur', 'change']
              }"
            >
              <div class="contacts">
                <NButton
                  type="primary"
                  ghost
                  @click="contactsModalVisible = true"
                >
                  选择督交人
                </NButton>

                <NScrollbar style="max-height: 210rem">
                  <div
                    v-show="formValue2.receivers?.length"
                    class="contacts-content"
                  >
                    <NTag
                      v-for="(contact, index) in formValue2.receivers"
                      @close="handleDeleteContact(index)"
                      :key="index"
                      closable
                      :color="{ color: '#ffffff' }"
                      style="justify-content: space-between; gap: 0 10rem"
                    >
                      {{ contact.typeName }}
                    </NTag>
                  </div>
                </NScrollbar>
              </div>
            </NFormItem>
          </NSpace>
        </NForm>
      </NSpace>
    </VDialogContent>
  </NModal>
  <NModal
    :auto-focus="false"
    v-model:show="contactsModalVisible"
    @close="contactsModalVisible = false"
  >
    <VScope
      @close="contactsModalVisible = false"
      @scopeSubmit="handleContactsModalSubmit"
      :default-list="formValue2.receivers"
      flat
    />
  </NModal>

  <!-- 暂存弹窗 -->
  <NModal
    :auto-focus="false"
    v-model:show="modalSaveVisible"
  >
    <VDialogContent
      @close="modalSaveVisible = false"
      @submit="submitSave"
      title="存放地"
    >
      <NSpace>
        <NForm
          ref="formRef"
          :model="formValue"
          :rules="rules"
          label-placement="left"
          :label-width="85"
          label-align="right"
          require-mark-placement="left"
        >
          <NSpace>
            <NFormItem
              label="存放位置:"
              path="storagePlace"
            >
              <NInput
                v-model:value="formValue.storagePlace"
                placeholder="请输入存放位置"
                clearable
                style="width: 250px"
              />
            </NFormItem>
          </NSpace>
          <NSpace>
            <NFormItem
              label="备注:"
              path="remark"
            >
              <NInput
                v-model:value="formValue.remark"
                placeholder="请输入备注"
                clearable
                type="textarea"
                style="width: 250px"
              />
            </NFormItem>
          </NSpace>
        </NForm>
      </NSpace>
    </VDialogContent>
  </NModal>
  <!-- 点交确认弹窗 -->
  <NModal
    :auto-focus="false"
    v-model:show="modalQrVisible"
  >
    <VDialogContent
      @close="modalQrVisible = false"
      @submit="againHandleQr"
      title="点交确认"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        是否对当前物品点交确认？
      </div>
    </VDialogContent>
  </NModal>
</template>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
// .box {
//   display: flex;
//   justify-content: space-between;
//   padding: 20rem;
//   .boxT {
//     width: 19%;
//     height: 100rem;
//     background-color: #ebebeb;
//     display: flex;
//     justify-content: center;
//     .imgS {
//       line-height: 140rem;
//       & > img {
//         width: 50rem;
//         height: 50rem;
//       }
//     }
//     .fontS {
//       margin-top: 14rem;
//       margin-left: 10px;
//       .topF {
//         font-size: 26px;
//         & > :first-child {
//           font-weight: 600;
//         }
//         & > :nth-child(2) {
//           font-size: 18px;
//         }
//       }
//       .bottomF {
//         font-size: 18px;
//       }
//     }
//   }
// }
// .line {
//   width: 100%;
//   height: 15px;
//   background-color: #f0efee;
// }

.contacts {
  display: flex;
  flex-direction: column;
  gap: 10rem 0;

  .n-button {
    max-width: 126rem;
  }

  .contacts-content {
    display: grid;
    grid-template-columns: repeat(5, auto);
    gap: 10rem;
    padding: 15rem;
    background-color: #fff;
  }
}
</style>
